package managedbean;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;

import model.Author;
import model.Book;

import org.apache.log4j.Logger;
import org.primefaces.model.UploadedFile;

import dao.BookDao;


@ManagedBean(name="bookBean")
@SessionScoped
public class BookManagedBean {

	public static Logger log = Logger.getLogger(BookListManagedBean.class);
	private Book book;
	private Long categoryId;
	private List<Long> authorsId;
	private UploadedFile file; //cf UploadedFile.getInputStream
    
	@ManagedProperty(value="#{bookDao}")
	private BookDao bookDao;

	@ManagedProperty(value="#{categoryListBean}")
	private CategoryListManagedBean categoryListManagedBean;
	@ManagedProperty(value="#{authorBean}")
	private AuthorManagedBean authorBean;
	    
	public BookDao getBookDao() {
		return bookDao;
	}
	
	public void setBookDao(BookDao bookDao) {
		this.bookDao = bookDao;
	}
	
	public CategoryListManagedBean getCategoryListManagedBean() {
		return categoryListManagedBean;
	}

	public void setCategoryListManagedBean(
			CategoryListManagedBean categoryListManagedBean) {
		this.categoryListManagedBean = categoryListManagedBean;
	}

	public AuthorManagedBean getAuthorBean() {
		return authorBean;
	}

	public void setAuthorBean(AuthorManagedBean authorBean) {
		this.authorBean = authorBean;
	}

	public Book getBook() {
		return book;
	}

	public void setBook(Book book) {
		this.book = book;
	}
	
	public Long getCategoryId() {
		return categoryId;
	}

	public void setCategoryId(Long categoryId) {
		this.categoryId = categoryId;
	}

	public List<Long> getAuthorsId() {
		return authorsId;
	}

	public void setAuthorsId(List<Long> authorsId) {
		this.authorsId = authorsId;
	}

	public String getCoverPath() {
		return "/resources/img/cover";
	}

	public UploadedFile getFile() {
		return file;	
	}

	public void setFile(UploadedFile file) {
		this.file = file;
	}

	public void validatePrice(FacesContext context, UIComponent toValidate, Object value) {
		double price = Double.valueOf(String.valueOf(value)); 
		if (price <= 0) {
			((UIInput)toValidate).setValid(false); 
			FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
			"Le prix doit être strictement supérieur à 0", "Le prix doit être strictement supérieur à 0"); 
			context.addMessage(toValidate.getClientId(context), message);
		}
	} 
	
	public void upload(Long bookId) {
		log.info("entrée dans upload");
		ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
		File result = new File(extContext.getRealPath("/resources/img") + "/cover" + bookId);
		log.info(extContext.getRealPath("/resources/img") + "/cover" + bookId);

		try {

			BufferedImage originalImage = ImageIO.read(file.getInputstream());
			int thumb_width = 150;
			int thumb_height = 300;
			BufferedImage resizedImage = new BufferedImage(thumb_width, thumb_height, originalImage.getType());
			Graphics2D g = resizedImage.createGraphics();
			g.drawImage(originalImage, 0, 0, thumb_width, thumb_height, null);
			g.dispose();

			ImageIO.write(resizedImage, "png", result);
			
		} catch (IOException e) {
			e.printStackTrace();

			FacesMessage error = new FacesMessage("The files were not uploaded!");
			FacesContext.getCurrentInstance().addMessage("Download", error);
		}
	}
	
	public String addBook() {
		setBook(new Book());
		return "addbook";
	}
	
	public String save() {
		getBook().setCategory(getCategoryListManagedBean().getCategoryById(getCategoryId()));
		for (Long id : getAuthorsId()) {
			getBook().addAuthor(getAuthorBean().getAuthorById(id));
		}
		getBookDao().save(getBook());
		log.info("insert id "+getBook().getId());
		upload(getBook().getId());
        FacesMessage message = new FacesMessage("Ajout du livre "+getBook().getTitle() + " effectué.");
        FacesContext.getCurrentInstance().addMessage(null, message);
        resetBookToAdd();
		return "bookAdded";
	}
	
	public void modify() {
		getBookDao().update(book);
		log.info("update id "+book.getId());
		if(file != null) {
			upload(book.getId());
		}
        FacesMessage message = new FacesMessage("Modification effectuée du livre "+book.getTitle() + ".");
        FacesContext.getCurrentInstance().addMessage(null, message);
	}
	
	public void delete(Book b) {
        getBookDao().delete(b);
        FacesMessage message = new FacesMessage("Suppression effectuée de "+b.getTitle() + ".");
        FacesContext.getCurrentInstance().addMessage(null, message);
	}

	public void deleteBookAuthor(Author a) {
		book.removeAuthor(a);
		getBookDao().update(book);
	}
	
	private void resetBookToAdd() {
		setBook(new Book());
	}
	
	@PostConstruct
	public void initBook() {
		resetBookToAdd();
	}
}
